package com.project.controller;

import com.project.bean.ProductBean;
import com.project.bean.ShopBean;
import com.project.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Collection;
import java.util.Map;

/**
 * 采购车应用控制器
 */
@RestController
@RequestMapping("buyShop")
public class BuyShopController {
    @Autowired
    private IShopService shopService;

    /**
     * 购买商品
     * @param option 操作
     * @param product 商品对象
     * @param buyNum 购买数量
     */
    @RequestMapping("buy")
    public String buy(String option, ProductBean product, MultipartFile productPic,
                      Integer buyNum, HttpServletRequest request) throws Exception{
        if("add".equals(option) && productPic.isEmpty() == false){
            //完成文件上传
            //得到上传文件名称
            String fileName = productPic.getOriginalFilename();
            //以时间毫秒数重命名文件
            fileName = System.currentTimeMillis()+
                    fileName.substring(fileName.lastIndexOf("."));
            //上传文件
            productPic.transferTo(new File("E:/project/server/pimg/"+fileName));
            //设置上传文件名
            product.setPicture(fileName);

        }
        //从session中，取出采购车
        Map<String,ShopBean> buyMap = (Map<String,ShopBean>)request.getSession().getAttribute("buyMap");
        //调用业务方法完成采购
        shopService.buy(option,product,buyNum,buyMap);


        return "ok";
    }

    /**
     * 从采购车中移除商品
     * @param productId 商品ID
     */
    @RequestMapping("removeBuy")
    public String remove(String productId, HttpServletRequest request){
        //从session中，取出采购车
        Map<String,ShopBean> buyMap = (Map<String,ShopBean>)request.getSession().getAttribute("buyMap");

        shopService.remove(productId,buyMap);
        return "ok";
    }

    /**
     * 修改采购车信息
     * @param productId 采购商品ID
     * @param buyPrice 采购价
     * @param buyNum 采购数量
     */
    @RequestMapping("updateBuyInfo")
    public String updateBuyInfo(String productId,Integer buyPrice,Integer buyNum,HttpServletRequest request){
        //从session中，取出采购车
        Map<String,ShopBean> buyMap = (Map<String,ShopBean>)request.getSession().getAttribute("buyMap");
        shopService.updateBuyInfo(productId,buyPrice,buyNum,buyMap);
        return "ok";
    }

    /**
     * 得到采购车信息
     * @return 采购车集合
     */
    @RequestMapping("getBuyList")
    public Collection<ShopBean> getBuyList(HttpServletRequest request){
        //从session中，取出采购车
        Map<String,ShopBean> buyMap = (Map<String,ShopBean>)request.getSession().getAttribute("buyMap");

        return buyMap.values();
    }


}
